<?php
namespace app\assets\controller;

use gdbase\CssMin;
use gdbase\JSMin;
use think\Controller;

/**
 * 资源压缩，缓存 css 和 js
 * Class Index
 * @package app\assets\controller
 */
class Index extends Controller
{
    private $assetsRoot = '';//本地文件目录
    public function index()
    {
        $this->assetsRoot = BASE_PATH;
        $MINIFY = true;
        $files = [];
        $success = [];
        $error = [];
        //cdn上存在的各种可能的文件类型
        $header = [
            'js' => 'application/x-javascript',
            'css' => 'text/css',
            'jpg' => 'image/jpg',
            'gif' => 'image/gif',
            'png' => 'image/png',
            'jpeg' => 'image/jpeg',
            'swf' => 'application/x-shockwave-flash'
        ];
//        $header = [
//            'js' => 'Content-Type: application/x-javascript',
//            'css' => 'Content-Type: text/css',
//            'jpg' => 'Content-Type: image/jpg',
//            'gif' => 'Content-Type: image/gif',
//            'png' => 'Content-Type: image/png',
//            'jpeg' => 'Content-Type: image/jpeg',
//            'swf' => 'Content-Type: application/x-shockwave-flash'
//        ];
        $type = '';
        $queryString = $_SERVER['QUERY_STRING'];
        $queryString = urldecode($queryString);
        foreach (explode(',',$queryString) as $key => $value) {
            if(empty($type)) {
                $type = $this->get_extend($value);
            }
            //文件存在
            if(file_exists($this->assetsRoot.$value)) {
                $in_str = file_get_contents($this->assetsRoot . $value);
                $success[] = $value;
                //处理文本
                if (preg_match('/js|css/', $type)) {
                    if ($MINIFY == true && $type == 'js') {
                        $files[] = JsMin::minify($in_str);
                    } else if ($MINIFY == true && $type == 'css') {
                        $files[] = CssMin::minify($in_str);
                    } else {
                        $files[] = $in_str;
                    }
                } else {
                    //处理非文本
                    $files[] = array($in_str);
                }
            }
            elseif (strstr($value, 'http://') || strstr($value, 'https://')){
                $in_str = file_get_contents($value);
                $success[] = $value;
                //处理文本
                if (preg_match('/js|css/', $type)) {
                    if ($MINIFY == true && $type == 'js') {
                        $files[] = JsMin::minify($in_str);
                    } else if ($MINIFY == true && $type == 'css') {
                        $files[] = CssMin::minify($in_str);
                    } else {
                        $files[] = $in_str;
                    }
                } else {
                    //处理非文本
                    $files[] = array($in_str);
                }
            }else{
                $error[] = $value;
            }
        }
        if(preg_match('/js|css/',$type)){
            $files = array_merge(
                ["/**********"],
//        ["\r\n * MidyCombo v1.0 (https://github.com/lovemidiuser/MidyCombo)"],
//        ["\r\n * Copyright 2017".(date('Y')>2017?date('-Y'):'')." MIDY,Ltd."],
//        ["\r\n **********"],
                ["\r\n * Time:".date('Y-m-d H:i:s')],
                ["\r\n * Success:"],[implode(' ,',$success)],
                ["\r\n * Failed:"],[implode(' ,',$error)],
                ["\r\n **********/"],
                ["\r\n"],
                $files
            );
        }
        header("Access-Control-Allow-Origin:'*'");
        header("Expires: " . date("D, j M Y H:i:s", strtotime("now + 10 years")) ." GMT");
//        header($header[$type]);//文件类型
        if(preg_match('/js|css/',$type)){
            $result = join("",$files);
        }else{
            //非文本的处理
            $result = join("",$files[0]);
        }
        $this->cache(md5($result));//etag,处理Etag是否多余?
//        echo $result;
        return response()->content($result)->contentType($header[$type]);
    }

    private function cache($etag){
//    $etag = $etag; //标记字符串，可以任意修改
        if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag){
            header('Etag:'.$etag,true,304);
            exit;
        }
        else header('Etag:'.$etag);
    }
    //得到扩展名
    private function get_extend($file_name) {
        $extend =explode("." , $file_name);
        $va=count($extend)-1;
        return $extend[$va];
    }
}
